/*
 * @lc app=leetcode.cn id=106 lang=cpp
 * @lcpr version=30204
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */


// @lcpr-template-start
using namespace std;
#include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// @lcpr-template-end
// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        // 最坏情况二叉树为单链表，需要递归n次，每次循环都要遍历当前子树的所有节点
        // 最后时间复杂度为O(n²)
        return _buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    }

    TreeNode* _buildTree(vector<int>& inorder, 
                    int ileft, int iright, 
                    vector<int>& postorder,
                    int pleft, int pright) {
        if (ileft > iright) return nullptr;

        TreeNode* root = new TreeNode(postorder[pright]);
        int mid = ileft;
        while(mid <= iright) {
            if (inorder[mid] != postorder[pright]) {
                mid++;
            }
            else {
                break;
            }
        }
        // 循环结束mid为中序遍历中根节点的下标
        root->left = _buildTree(inorder, ileft, mid - 1, 
                                postorder, pleft, pleft + mid - ileft - 1);
        root->right = _buildTree(inorder, mid + 1, iright, 
                                postorder, pleft + mid - ileft, pright - 1);
        return root;
    }
};
// @lc code=end



/*
// @lcpr case=start
// [9,3,15,20,7]\n[9,15,7,20,3]\n
// @lcpr case=end

// @lcpr case=start
// [-1]\n[-1]\n
// @lcpr case=end

 */

